/**
 * Created with IntelliJ IDEA.
 * User: teddy zhang
 * Date: 2015-07-25
 * Time: 17:48
 */
define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    
    require('./markingReportDetail');
    
    $.widget('rk.markingReportCtrl', {
        //create方法中用来生成html
        _create: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;


            rk.get('/json/crm_wanxue/init-report.action', function(data) {
                if (data.status === 0) {
                    data = data.data;
                    me._render(data);
                    me._bind(data);
                    me._search(1);
                }
            });

        },


        _render: function(data) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            elem.html(rk.templateText(require('oa/tmpl/wanxue/tpl_marking_report.tpl'),data.entity));

        },

        _bind:function(data) {
            var me = this;
            var elem = me.element;
            var opt = me.options;


            $("#wanXueReportUser").rkUser({
                onSelect: function(userId, userName) {
                    elem.find('.grid_tool a.search-close').show();
                    me._search(1);
                }
            });


            $("#wanXueReportDepartment").singletreepicker({
                position: {
                    my: 'left top+2'
                },
                menuWidth: 200,
                source: '/json/crm_dimension/dim-tree.action?dimType=1&belongId=25',
                onSuccess: function (o) {
                    //var value = p.value;
                    $('#wanXueReportDepartment span.view_name').attr("data-value",o.value).html(o.label);
                    $("#wanXueReportUser").attr('userid','').val('');
                    elem.find('.grid_tool a.search-close').hide();
                    me._search(1);
                }
            });


            elem.find('.grid_tool a.search-close').on('click', function(event) {
                var _this = this;
                $("#wanXueReportUser").attr('userid','').val('');
                elem.find('.grid_tool a.search-close').hide();
                me._search(1);
            });


        },
        _getSearchData: function(pageNo,pageSize) {
            var me = this;
            var elem = me.element;

            var postDATA = {};
            postDATA.departId = $('#wanXueReportDepartment span.view_name').attr("data-value");
            postDATA.userIds = $("#wanXueReportUser").attr('userid');
            postDATA.page = pageNo;
            postDATA.size = pageSize;
            return postDATA;
        },



        _sort: function(data) {
            var sortedDATAArray = [];
            $.each(data, function(index, item) {
                if (item && item.userId == SESSION.user.id) {
                    sortedDATAArray[0] = item;
                    index--;
                } else {
                    sortedDATAArray[index + 1] = item;
                }
            });
            return $.grep(sortedDATAArray, function(item, i) {
                return (item);
            });
        },


        _search:function(pageNo){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var pageSize = 10;
            elem.find('span.wx-dep-count span').text(0);
            //
            elem.find('.wx-grid-body').beLoading({
                label:'统计时间较长，请耐心等待',
                size: 'large'
            })


            rk.post("/json/crm_wanxue/list-report.action", me._getSearchData(pageNo,pageSize), function(json) {
                if (json.status === 0) {
                    var listData = json.data.results;
                    var total = json.data.total;

                    var  tbody_content = '<div class="default_page"><div class="ico"></div><p>'+rk.i18n('WORKREPORT_2')+'</p></div>';
                    listData = me._sort(listData);
                    $.each(listData, function (i, o) {
                        var diffMonths = moment(moment().toDate().getTime()).diff(moment(o.joinAt),'months');
                        var diffYear = parseInt(diffMonths/12);
                        var diffMonth = diffMonths%12;
                        o.joinAt = o.joinAt? (diffYear?diffYear+'年':'')+diffMonth+ '个月':'';

                        var starStyle;
                        switch (parseFloat(o.starLevel)){
                            case 1:
                                starStyle = 'one';
                                break;
                            case 2:
                                starStyle = 'two';
                                break;
                            case 3:
                                starStyle = 'three';
                                break;
                            case 4:
                                starStyle = 'four';
                                break;
                            case 5:
                                starStyle = 'five';
                                break;
                            default:
                                starStyle = '';
                        }
                        o.starLevel = starStyle;
                        o.percentage = ((parseFloat( (o.actualTarget && o.performanceTarget)?o.actualTarget:0)/ parseFloat(o.performanceTarget?o.performanceTarget:100) ).toFixed(2))*100;
                        if(o.percentage > 100)o.percentage = 100;
                    });
                    if(total != 0){
                        json.data.results = listData;
                        tbody_content = rk.templateText(require('oa/tmpl/wanxue/tpl_marking_report_content.tpl'), json.data);
                    }


                    var pagingdiv = elem.find("div.rk-paging");
                    pagingdiv.rkPaging({
                        pagenum: pageNo, //（可选）当前页数，默认1
                        pagesize: pageSize, //（可选）当前每页显示条数，默认20
                        rowscount: total, //所有数据数
                        onChange: function(pagenum) {
                            me._search(pagenum);
                        }
                    });

                } else if (json.status === 300001) {
                    tbody_content =  '<div class="default_page"><div class="ico"></div><p>'+rk.i18n('WORKREPORT_1')+'</p></div>'

                } else {
                    rk.noticeError(rk.i18n('ERROR_SYSTEM'));
                }
                elem.find('span.wx-dep-count span').text(total);
                elem.find('.wx-grid-body').html(tbody_content).beScroll();

            });




        }
    });
    return {
        init: function() {
            var $crmPanel = rk.showPageView('crm-panel');
            var $contentPanel = $crmPanel.find('.container_content');

            $contentPanel.detailPopup({
                widgetName: 'markingReportDetail',
                selector: 'a.js_wan_xue_user_name',
                target: '#div_detail_frame'
            })

            $contentPanel.markingReportCtrl();


        }
    }
});